package com.ym.b2b.sys.db.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.SequenceInputStream;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ym.b2b.commons.controller.BaseController;
import com.ym.b2b.commons.util.CheckData;
import com.ym.b2b.sys.db.OracleBackBean;
import com.zc.commons.base.Result;

@Controller
@RequestMapping("/db")
public class DbBackController extends BaseController {

    /**
     * 备份oracle
     * 
     * @Title: backOracleDB
     * @Description: TODO
     * @Param @param oracleBackBean
     * @Param @return
     * @Return Result
     * @Throws
     */
    @RequestMapping("backOracleDB.do")
    @ResponseBody
    public Result backOracleDB(OracleBackBean oracleBackBean) {
        Result ret = new Result();

        try {
            Process process = Runtime.getRuntime().exec("cmd");
            SequenceInputStream sis = new SequenceInputStream(process.getInputStream(), process.getErrorStream());
            InputStreamReader isr = new InputStreamReader(sis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            // next command
            OutputStreamWriter osw = new OutputStreamWriter(process.getOutputStream());
            BufferedWriter bw = new BufferedWriter(osw);
            String fileName = oracleBackBean.getUser() + "_" + CheckData.getDate();
            bw.write("exp " + oracleBackBean.getUser() + "/" + oracleBackBean.getPwd() + "@" + oracleBackBean.getSid()
                     + " owner=" + oracleBackBean.getUser() + " file=" + oracleBackBean.getSavePath() + "" + fileName
                     + ".dmp log=" + fileName + ".log");
            bw.newLine();

            bw.flush();
            bw.close();
            osw.close();
            // read
            String line = null;
            while (null != (line = br.readLine())) {
                System.out.println(line);
            }
            process.destroy();
            br.close();
            isr.close();
            System.out.println(" ---备份完成");
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, "备份异常：" + e.getMessage());
        }
        return ret;
    }

}
